package com.tykhome.evernote.evernote2kindle.service.impl;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Properties;

import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import com.evernote.edam.type.Note;

/**
 * spring 发送邮件的demo
 * 
 * @author sunlightcs 2011-4-20 http://hi.juziku.com/sunlightcs/
 * 
 */
public class SendMail {
	
	/**
	 * 发送邮件
	 * 
	 * @param send
	 *            发件人
	 * @param mailTitle
	 *            邮件主题
	 * @param mailText
	 *            邮件内容
	 * @param mailAddress
	 *            接收邮件的地址
	 * @return true表示发送邮件成功,false表示发送邮件失败
	 */
	public static boolean sendMail(String send, String mailTitle, Note note,
			String mailAddress) {
		boolean flag = true;
		try {

			JavaMailSenderImpl sender = new JavaMailSenderImpl();
			Properties prop = new Properties();
			sender.setHost("smtp.qq.com");
			sender.setUsername("tian_yongke@qq.com");
			sender.setPassword("901125tyk");
			sender.setPort(465);

			/**
			 * 如果要使用用户名和密码验证,这一步需要
			 */
			prop.setProperty("mail.smtp.auth", "true");
			/**
			 * SSL 连接发送
			 */
			prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
			/**
			 * 设置发送邮件的延迟时间
			 */
			prop.setProperty("mail.smtp.timeout", "36000");
			sender.setJavaMailProperties(prop);

			MimeMessage mailMessage = sender.createMimeMessage();
			// 设置utf-8或GBK编码，否则邮件会有乱码
			MimeMessageHelper messageHelper = new MimeMessageHelper(
					mailMessage, true, "utf-8");
			messageHelper.setTo(mailAddress);
//			messageHelper.setFrom(MimeUtility.encodeText(send)
//					+ " <no-reply@xxx.com>");
			messageHelper.setFrom(send);
			messageHelper.setSubject(mailTitle);
			// true表示启动HTML格式的邮件
			messageHelper.setText(note.getTitle(), true);
			File tmp = new File("tmp/" + note.getTitle() + ".html");
			BufferedWriter bfw = new BufferedWriter(new FileWriter(tmp));
			bfw.write(note.getContent());
			bfw.flush();
			bfw.close();
//			messageHelper.addAttachment(MimeUtility.encodeWord(note.getTitle()), tmp); 
			messageHelper.addAttachment(MimeUtility.encodeWord(note.getTitle() + ".html"), tmp);
//			messageHelper.addAttachment(note.getTitle() + ".html", tmp); 
//			sender.send(mailMessage);
//			tmp.delete();
		} catch (Exception ex) {
			flag = false;
			ex.printStackTrace();
		}

		return flag;

	}
}